<template>
  <section class="todoapp">
    <TodoHeader @add="addFn" />
    <TodoMain
      :list="showList"
      @del="delFn"
      @change="changeFn"
      @checkAll="checkAllFn"
    />
    <TodoFooter :list="showList" @clear="clearFn" @changeType="changeType" />
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type: 'all',
    }
  },
  methods: {
    delFn(id) {
      // 把id过滤掉
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeFn(id) {
      const result = this.list.find((item) => item.id === id)
      result.isDone = !result.isDone
    },
    addFn(name) {
      this.list.unshift({
        id: Date.now(),
        name,
        isDone: false,
      })
    },
    clearFn() {
      // console.log('清空')
      this.list = this.list.filter((item) => item.isDone === false)
    },
    changeType(type) {
      this.type = type
    },
    checkAllFn(value) {
      this.list.forEach((item) => (item.isDone = value))
    },
  },
  computed: {
    showList() {
      if (this.type === 'completed') {
        // 显示已完成
        return this.list.filter((item) => item.isDone === true)
      } else if (this.type === 'active') {
        // 显示未完成
        return this.list.filter((item) => item.isDone === false)
      } else {
        return this.list // 全部显示
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        localStorage.setItem('todoList', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
